package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

func main() {
	filePath := "D:\\code_zch\\code_script_bat_sh\\git-manage\\my-repo-2.txt"
	resultLogPath := "result.log"
	checkRepositories(filePath, resultLogPath)
}

func checkRepositories(filePath string, resultLogPath string) {
	file, err := os.Open(filePath)
	if err != nil {
		logToFile(resultLogPath, fmt.Sprintln("Error opening the file:", err))
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			logToFile(resultLogPath, fmt.Sprintln("Error closing the file:", err))
		}
	}(file)

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		repoPath := scanner.Text()
		repoPath = strings.TrimSpace(repoPath) // Remove any leading/trailing whitespaces.
		if repoPath == "" {
			continue // Skip empty lines
		}

		status, err := getGitStatus(repoPath)
		if err != nil {
			logToFile(resultLogPath, fmt.Sprintln("Repository:", repoPath, "Error:", err))
			continue
		}

		if status == "" {
			logToFile(resultLogPath, fmt.Sprintln("Repository:", repoPath, "Status: No changes."))
		} else {
			// logToFile(resultLogPath, fmt.Sprintln("Repository:", repoPath, "Status: Changes detected.\n", status))
			// 只需要输出有变更的文件名即可
			logToFile(resultLogPath, fmt.Sprintln("Repository:", repoPath, "Status: Changes detected"))
		}
	}

	if err := scanner.Err(); err != nil {
		logToFile(resultLogPath, fmt.Sprintln("Error reading the file:", err))
	}
}

func getGitStatus(repoPath string) (string, error) {
	cmd := exec.Command("git", "-C", repoPath, "status", "--porcelain")
	output, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error opening the file:", err)
		return "", err
	}
	return string(output), nil
}

func logToFile(filename, message string) {
	f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		logToFile(err.Error(), fmt.Sprintln("Error opening log file:", err))
		return
	}
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			logToFile(err.Error(), fmt.Sprintln("Error closing log file:", err))
		}
	}(f)

	if _, err := f.WriteString(message); err != nil {
		fmt.Println("Error writing to log file:", err)
	}
}
